package com.lej.core.widget.customview

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.constraintlayout.widget.ConstraintLayout
import com.lej.core.R
import com.lej.core.base.statusHeight
import com.lej.core.dsl.margin_top_px
import com.lej.core.utils.extention.getDrawableCompat

/**
 *  author: cjq
 *  date  : 2022/4/19 0019
 *  desc  :
 */
class CustomTitle(
    context: Context,
    attrs: AttributeSet? = null
) :
    ConstraintLayout(context, attrs) {

    var tvTitle: TextView? = null
    var tvRight: TextView? = null
    var iconLeft: AppCompatImageView? = null
    val titlePadding = 20

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_custom_title, this, true)
        attrs?.let { retrieveAttributes(context, it, view) }
    }

    fun setTitleText(text: String) {
        tvTitle?.text = text
    }

    private fun retrieveAttributes(context: Context, attributes: AttributeSet, view: View) {
        val typeArray = context.obtainStyledAttributes(attributes, R.styleable.CustomTitle)
        val textTitle = typeArray.getText(R.styleable.CustomTitle_titleText)
        val textRight = typeArray.getText(R.styleable.CustomTitle_titleTextRight)
        val drawableLeft = typeArray.getDrawable(R.styleable.CustomTitle_titleDrawableLeft)

        tvTitle = view.findViewById(R.id.tv_custom_title)
        tvRight = view.findViewById(R.id.tv_custom_right)
        iconLeft = view.findViewById(R.id.icon_custom_left)

        tvTitle?.margin_top_px = statusHeight + titlePadding
        textTitle?.let {
            tvTitle?.text = textTitle
        }
        textRight?.let {
            tvRight?.text = textRight
        }
        if (drawableLeft == null) {
            iconLeft?.setImageDrawable(context.getDrawableCompat(R.drawable.ic_back))
        } else {
            iconLeft?.setImageDrawable(drawableLeft)
        }
        typeArray.recycle()
    }

}